import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/utils/log_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/back_icon.dart';
import 'package:xws/widgets/loading_icon.dart';
import 'package:xws/widgets/safe_appbar.dart';
import 'package:xws/widgets/safe_scaffold.dart';

/// 视频预览
class VideoViewer extends StatefulWidget {
  const VideoViewer({
    Key? key,
    required this.videos,
    this.initIndex = 0,
    this.autoPlay = false,
  }) : super(key: key);

  final List<String> videos;
  final int initIndex;
  final bool autoPlay;

  @override
  State<VideoViewer> createState() => _VideoViewerState();
}

class _VideoViewerState extends State<VideoViewer> with SafeState<VideoViewer> {
  late PageController _controller;
  late int _currentIndex = widget.initIndex + 1;

  @override
  void initState() {
    super.initState();
    _controller = PageController(initialPage: widget.initIndex);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeScaffold(
      overlayStyle: SystemUiOverlayStyle.light,
      backgroundColor: Colors.black,
      appBar: SafeAppBar(
        titleText: '$_currentIndex/${widget.videos.length}',
        titleTextStyle: const TextStyle(color: Colors.white),
        appBarColor: Colors.transparent,
        leading: BackIcon(color: white(context)),
      ),
      body: PageView.builder(
        controller: _controller,
        itemCount: widget.videos.length,
        scrollDirection: Axis.vertical,
        onPageChanged: (int p) => safeSetState(() => _currentIndex = p),
        itemBuilder: (_, int index) {
          return _VerticalVideo(path: widget.videos[index]);
        },
      ),
    );
  }
}

enum _PlayStatus { idle, buff, init, playing }

///竖屏全屏播放器
class _VerticalVideo extends StatefulWidget {
  const _VerticalVideo({
    Key? key,
    required this.path,
    this.loop = false,
    this.autoPlay = false,
  }) : super(key: key);

  @override
  _VerticalVideoState createState() => _VerticalVideoState();

  final String path;
  final bool loop;
  final bool autoPlay;
}

class _VerticalVideoState extends State<_VerticalVideo> with SafeState<_VerticalVideo> {
  late VideoPlayerController _controller;

  _PlayStatus _playStatus = _PlayStatus.idle;

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void dispose() {
    _controller.removeListener(_playingListener);
    _controller.dispose();
    super.dispose();
  }

  ///初始化
  Future<void> _init() async {
    if (widget.path.startsWith('http')) {
      _controller = VideoPlayerController.network(widget.path);
    } else if (widget.path.startsWith('videos')) {
      _controller = VideoPlayerController.asset(widget.path);
    } else if (widget.path.startsWith('/')) {
      _controller = VideoPlayerController.file(File(widget.path));
    }

    debug(_controller.dataSource);
    _controller.setVolume(1);
    _controller.addListener(_playingListener);

    await _controller.initialize();

    if (widget.autoPlay) await _play();
  }

  ///播放监听
  Future<void> _playingListener() async {
    if (_controller.value.isPlaying) {
      if (_playStatus != _PlayStatus.playing) {
        safeSetState(() => _playStatus = _PlayStatus.playing);
      }
    }

    if (_controller.value.isBuffering) {
      if (_playStatus != _PlayStatus.buff) {
        safeSetState(() => _playStatus = _PlayStatus.buff);
      }
    }

    if (_controller.value.isInitialized && _playStatus == _PlayStatus.idle) {
      if (_playStatus != _PlayStatus.init) {
        safeSetState(() => _playStatus = _PlayStatus.init);
      }
    }

    if (_controller.value.duration == _controller.value.position) {
      safeSetState(() => _playStatus = _PlayStatus.init);
    }
  }

  ///自动判断播放暂停
  Future<void> _autoPlayPause() async {
    try {
      if (_controller.value.isPlaying) {
        await _pause();
        return;
      } else {
        await _play();
      }
    } catch (e) {
      error('_autoPlayPause:$e');
    }
  }

  ///播放
  Future<void> _play() async {
    try {
      await _controller.play();
    } catch (e) {
      debug('播放视频出错:$e');
    }
  }

  ///暂停
  Future<void> _pause() async {
    try {
      await _controller.pause();
    } catch (e) {
      error('暂停出错:$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        /// 视频
        if (_controller.value.isInitialized) _buildVideoBody,

        /// 中间播放暂停按钮
        _buildPlayBtn,
      ],
    );
  }

  ///视频主体
  Widget get _buildVideoBody {
    return Center(
      child: AspectRatio(
        aspectRatio: _controller.value.aspectRatio,
        child: VideoPlayer(_controller),
      ),
    );
  }

  ///构建暂停播放按钮
  Widget get _buildPlayBtn {
    if (_playStatus == _PlayStatus.playing) {
      return const SizedBox.shrink();
    } else if (_playStatus == _PlayStatus.idle || _playStatus == _PlayStatus.buff) {
      return Container(
        width: 80,
        height: 80,
        alignment: Alignment.center,
        child: const LoadingIcon(size: 30, color: Colors.white),
        decoration: const BoxDecoration(color: Colors.white30, shape: BoxShape.circle),
      );
    }

    return AppBtn.noPadding(
      onTap: _autoPlayPause,
      child: const Icon(
        Icons.play_circle_fill_rounded,
        color: Colors.white,
        size: 78,
      ),
      alignment: Alignment.center,
      color: Colors.white30,
      width: 80,
      height: 80,
      radius: 50,
    );
  }
}
